package DataStructure.heapAndPriorityQueue;

import java.util.ArrayList;

public class MaxHeap<E extends Comparable> {
    private ArrayList<E> data;

    public MaxHeap() {
        data = new ArrayList<>();
    }

    public MaxHeap(int capacity) {
        data = new ArrayList<>(capacity);
    }

    public MaxHeap(E[] arr) {
        data = new ArrayList<>(arr.length);
        for (int i = 0; i < arr.length; i++) {
            data.add(arr[i]);
        }
        for (int i = parent(arr.length - 1); i >= 0; i--) {
            siftDown(i);
        }
    }

    public int size() {
        return data.size();
    }

    public boolean isEmpty() {
        return data.isEmpty();
    }

    private int parent(int index) {
        if (index == 0) {
            throw new IllegalArgumentException("index is invalid");
        }
        return (index - 1) / 2;
    }

    private int leftChild(int index) {
        return index * 2 + 1;
    }

    private int rightChild(int index) {
        return index * 2 + 2;
    }

    public void add(E e) {
        data.add(e);
        siftUp(data.size() - 1);
    }

    private void swap(int i, int j) {
        if (i < 0 || j < 0 || i == j) {
            return;
        }
        E t = data.get(i);
        data.set(i, data.get(j));
        data.set(j, t);
    }

    private void siftUp(int index) {
        while (index > 0 && data.get(index).compareTo(data.get(parent(index))) > 0) {
            swap(index, parent(index));
            index = parent(index);
        }
    }

    public E getMax() {
        if (data.isEmpty()) {
            throw new IllegalArgumentException("heap is empty");
        }
        return data.get(0);
    }

    public E extractMax() {
        E ret = getMax();
        data.set(0, data.get(data.size() - 1));
        data.remove(data.size() - 1);
        siftDown(0);
        return ret;
    }

    private void siftDown(int index) {
        while (leftChild(index) < data.size()) {
            int j = leftChild(index);
            if (j + 1 < data.size() && data.get(j + 1).compareTo(data.get(j)) > 0) {
                j = rightChild(index);
            }
            if (data.get(index).compareTo(data.get(j)) > 0) {
                break;
            }
            swap(index, j);
            index = j;
        }
    }

    /**
     * 取出最大的元素 并替换成e
     */
    public E replace(E e) {
        E ret = getMax();
        data.set(0, e);
        siftDown(0);
        return ret;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (E e : data) {
            stringBuilder.append(e + " ");
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
